/**
 * Created by xiaoz on 16/8/13.
 */
// 日期选择控件
// ---
// config参数说明：
// value: 默认值
// pos: 下拉选择控件出现在input的位置


define(["utils", "base"], function (utils, baseClass) {


    var Component = function (config) {
        var _this = this;
        Component.baseConstructor.call(this, config);
        this.pos = config.pos || "bottom";
        this.$el.addClass("yy-datepicker");
        this.readonly = config.readonly||false;
        if (this.readonly) {
            this.input = $("<input type='text' readonly='readonly'/>");
        } else {
            this.input = $("<input type='text'/>");

        }

        this.$el.append(this.input);
        this.$el.on('keydown', function (e) {
            if (e.keyCode !== 8) {
                e.stopPropagation();
                e.preventDefault();
                e.returnValue = false;
                return;
            } else {
                if(!_this.readonly){
                    _this.input.val("");
                }
            }

        });
        this.$el.bind("click", function (e) {
            if (_this.disabled) {
                return;
            }
            e.stopPropagation();
            e.preventDefault();
            _this.pageview.pageManager.triggerBodyClickWithoutSelf(_this);
            _this.show();
        });
        if (config.value === "") {
            this.value = "";
        } else {
            this.value = utils.convertToDate(config.value);
        }

        this.nowDate = new Date();

        this.init();
        if (config.value) {
            this.selectedValue = this.value;
            if (config.value === "") {
                this.selectedValueStr = "";
            } else {
                this.selectedValueStr = utils.ConvertDateToStr(this.value);
            }
        }

        var changeMethodName = config.comKey + "_change";
        this.changeMethod = this.pageview.plugin[changeMethodName];

        //TODO: 参照dropdown组件的方式，后续可以优化这个方案
        this.hideCb = config.hideCb ? config.hideCb : false;
        this.showCb = config.showCb ? config.showCb : false;
    }

    utils.extendClass(Component, baseClass);

    Component.prototype.click = function () {
        this.$el.click();
    };

    Component.prototype.itemClick = function (e) {
        e.stopPropagation();
        e.preventDefault();
        var date_str = e.target.getAttribute('data-str');
        if (date_str) {
            this.input.val(date_str);
            this.selectedValueStr = date_str;
            this.selectedValue = utils.convertToDate(date_str);
            this.value = this.selectedValue;
            this.hide();
            if (this.changeMethod) {
                this.changeMethod.call(this.pageview.plugin, this, {
                    date: this.selectedValue,
                    str: this.selectedValueStr
                });
            }
        }

    };

    Component.prototype.getValue = function () {

        if (this.input && this.input.val() === "") {
            return {
                str: this.input.val()
            };
        } else {
            return {
                date: this.selectedValue,
                str: this.selectedValueStr
            };
        }
    };

    Component.prototype.upDateUI = function (val) {
        var dateArr = utils.getDaysArrInCanledar(val);
        this.timeBody.empty();
        var dateInfo = utils.getDateInfo(val);
        var curDateStr = utils.ConvertDateToStr(this.selectedValue);
        var nowDateInfo = utils.getDateInfo(this.nowDate);
        var nowDateStr = nowDateInfo.year + "-" + nowDateInfo.monthStr + "-" + nowDateInfo.dayStr;
        for (var i = 0, j = dateArr.length; i < j; i++) {
            var item = dateArr[i];
            var markClassName = "yy-datepicker-item-" + item.mark;
            var isSelected = item.dateStr === curDateStr;
            var isToday = item.dateStr === nowDateStr;
            var todayClass = isToday ? "yy-datepicker-item-today" : "";
            var className = isSelected ? "yy-datepicker-item yy-datepicker-item-selected " + markClassName : "yy-datepicker-item " + markClassName;
            var li = $("<li data-str='" + item.dateStr + "' class='" + className + ' ' + todayClass + "'>" + item.day + "</li>");
            if (isSelected) {
                this.curLi = li;
            }
            this.timeBody.append(li);
        }
        this.value = utils.convertToDate(val);


        this.yearLabel.html(dateInfo.year);
        this.monthLabel.html(dateInfo.monthStr);
    };

    Component.prototype.setValue = function (val) {
        var dateStr = "";
        if (val === "") {

        } else {
            var dateInfo = utils.getDateInfo(val);
            dateStr = dateInfo.year + "-" + dateInfo.monthStr + "-" + dateInfo.dayStr;
            this.upDateUI(val);
        }
        this.input.val(dateStr);
        this.oldValue = utils.copy(this.value);
        this.selectedValue = this.value;
        this.selectedValueStr = dateStr;

    };

    Component.prototype.hide = function () {
        this.dropdown.css({
            visibility: "hidden",
            left: -1000
        });
        this.hideCb && this.hideCb();
        this.pageview.pageManager.cancelBodyClick(this.id);
    };

    Component.prototype.show = function (val, posPara) {
        var _this = this;


        this.showCb && this.showCb();

        if (!posPara) {
            var pos = this.$el.offset();
            var h = this.$el.height();
            var top = pos.top + h + 4;
            if (this.pos === "top") {
                top = pos.top - h - 255;
            } else {

            }
            var offset = this.config.offset || {
                    x: 0,
                    y: 0
                };
            var x = offset.x || 0;
            var y = offset.y || 0;

            this.dropdown.css({
                top: (top + y) + "px",
                left: (pos.left + x) + "px",
                "visibility": "visible"
            });
        } else {
            this.dropdown.css({
                top: posPara.top + "px",
                left: posPara.left + "px",
                "visibility": "visible"
            });
        }

        this.pageview.pageManager.regeistBodyClick(this.id, function () {
            _this.hide();
        });
        val = val || this.value;
        this.selectedValue = val;
        this.upDateUI(val);
    };
    Component.prototype.goPreYear = function (e) {
        var date = utils.getPreYear(this.value);
        this.upDateUI(date);
    };
    Component.prototype.goNextYear = function (e) {
        var date = utils.getNextYear(this.value);
        this.upDateUI(date);
    };
    Component.prototype.goPreMonth = function (e) {
        var date = utils.getPreMonth(this.value);
        this.upDateUI(date);
    };
    Component.prototype.goNextMonth = function (e) {
        var date = utils.getNextMonth(this.value);
        this.upDateUI(date);
    };


    Component.prototype.showYears = function (e) {

    };
    Component.prototype.initYearMontSwitchArea = function (wrapper) {
        var _this = this;
        var yearLeftWrapper = $("<div class='yy-year-left'><span class='yy-fontawesome'></span></div>");
        yearLeftWrapper.bind("click", function (e) {
            _this.goPreYear(e);
        });
        this.yearLabel = $("<div class='yy-year-label'></div>");
        this.yearLabel.bind("click", function (e) {
            _this.showYears(e);
        });
        var yearRightWrapper = $("<div class='yy-year-right'><span class='yy-fontawesome'></span></div>");
        yearRightWrapper.bind("click", function (e) {
            _this.goNextYear(e);
        });
        var monthLeftWrapper = $("<div class='yy-month-left'><span class='yy-fontawesome'></span></div>");
        monthLeftWrapper.bind("click", function (e) {
            _this.goPreMonth(e);
        });
        this.monthLabel = $("<div class='yy-month-label'></div>");
        var monthRightWrapper = $("<div class='yy-month-right'><span class='yy-fontawesome'></span></div>");
        monthRightWrapper.bind("click", function (e) {
            _this.goNextMonth();
        });
        wrapper.append(yearLeftWrapper).append(this.yearLabel).append(yearRightWrapper).append(monthLeftWrapper).append(this.monthLabel).append(monthRightWrapper);
    };
    Component.prototype.init = function () {
        var _this = this;
        var wrapperClassName = this.config.wrapperClassName || "";
        this.dropdown = $("<div class='yy-datepicker-warpper " + wrapperClassName + "'></div>");
        var yearMonthSwitchArea = $("<div class='yy-datepicker-yearmonth-wrap'></div>");
        this.initYearMontSwitchArea(yearMonthSwitchArea);
        var yearmonthdayWrapper = $("<div class='yy-datepicker-yearmonthday-wrap'></div>");
        this.daywrapper = $("<div class='yy-datepicker-daywrap'></div>");
        var header = $("<div class='yy-datepicker-header'><span>日</span><span>一</span><span>二</span><span>三</span><span>四</span><span>五</span><span>六</span></div>");
        this.dropdown.append(header);
        this.dropdown.bind("click", function (e) {
            _this.itemClick(e);
        });
        this.timeBody = $("<ul></ul>");

        this.daywrapper.append(header).append(this.timeBody);
        yearmonthdayWrapper.append(this.daywrapper);

        this.dropdown.append(yearMonthSwitchArea).append(yearmonthdayWrapper);

        this.pageview.$el.append(this.dropdown);
        this.setValue(this.value);
    }

    return Component;
});
